<template>
  <div class="container">
    <!-- 搜索和操作区域 -->
    <div class="operation-panel">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="题库名称">
          <el-input v-model="searchForm.name" placeholder="请输入题库名称" clearable />
        </el-form-item>
        <el-form-item label="科目">
          <el-select v-model="searchForm.subjectId" placeholder="请选择科目" clearable>
            <el-option v-for="subject in subjectOptions" :key="subject.id" :label="subject.name" :value="subject.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>添加题库
        </el-button>
      </div>
    </div>

    <div></div>
    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="题库名称" min-width="150" />
      <el-table-column prop="code" label="题库编码" width="120" />
      <el-table-column label="所属科目" width="120">
        <template #default="{ row }">
          {{ getSubjectName(row.subjectId) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="公开" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isPublic === 1 ? 'success' : 'info'">
            {{ row.isPublic === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="questionCount" label="题目数" width="100" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="300" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" @click="openQuestionBank(row.id)">添加题目</el-button>
          <el-button size="small" @click="openQuestionBank2(row.id)">管理题库</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData" @current-change="fetchData" />
    </div>


    <Dialog v-model="showQuestionBank" title="添加题目" width="1000px" @close="handleClose">
      <div style="overflow-y: auto; margin: 0 auto; " v-if="showQuestionBank">
        <QuestionSelect :questionBankId="questionBankId"  :isManage="isManage" >
          <!-- 使用作用域插槽 -->
          <template #action="{ selectedQuestions }">

            <div v-if="isManage" @click="handleSelectQuestions(selectedQuestions)">
             <CuteButton text="移出题库">
            </CuteButton>
            </div>

            <div v-else @click="handleSelectQuestions(selectedQuestions)">
              <CuteButton text="导入">
            </CuteButton>
            </div>

          </template>
        </QuestionSelect>

      </div>

    </Dialog>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="题库名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="题库编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入题库编码" />
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectId">
          <el-select v-model="formData.subjectId" placeholder="请选择科目">
            <el-option v-for="subject in subjectOptions" :key="subject.id" :label="subject.name" :value="subject.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="题库描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入题库描述" />
        </el-form-item>
        <el-form-item label="默认分值">
          <el-input-number v-model="formData.score" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="难度">
          <el-rate v-model="formData.difficulty" :max="5" show-score />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" active-text="启用"
            inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="公开题库">
          <el-switch v-model="formData.isPublic" :active-value="1" :inactive-value="0" active-text="公开"
            inactive-text="私有" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { QuestionBankService } from '@/api/questionBank'
import { SubjectService } from '@/api/questionBank'
import Dialog from '@/components/commont/Dialog.vue';
const { getQuestionBankPage, addQuestionBank, updateQuestionBank, deleteQuestionBank, getSubjectList, addQuestionBankBatch } = QuestionBankService
const { getSubjectTree } = SubjectService;
import CuteButton from '@/components/commont/CuteButton.vue'
// 表格数据
const tableData = ref([])
const loading = ref(false)
const subjectOptions = ref([])
const subjectTree = ref([])
const showQuestionBank = ref(false)
const questionBankId = ref(null)
const isManage = ref(false)
// 搜索表单
const searchForm = reactive({
  name: '',
  subjectId: null
})

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

const handleClose = () => {
  showQuestionBank.value = false
}
const handleCustomAction = (questions) => {
  console.log('获取到子组件数据:', questions);
  // 这里可以处理提交逻辑
}
const openQuestionBank = (id) => {
  isManage.value = false
  questionBankId.value = id
  showQuestionBank.value = true
}
const openQuestionBank2 = (id) => {

  isManage.value = true
  questionBankId.value = id
  showQuestionBank.value = true
}

// 选择题目
const selectedQuestionIds = ref([])
const handleSelectQuestions = (quList) => {
  console.log("parrrrrrr", quList)
  quList.forEach((item) => {
    const data = {
      bankId: questionBankId.value,
      questionId: item.id,
    }
    selectedQuestionIds.value.push(data)
  })
  console.log("selectedQuestionIds", selectedQuestionIds.value)
  if (selectedQuestionIds.value.length === 0) {
    ElMessage.warning('请至少选择一题')
    return
  }
  if(isManage.value){
  alert("移出题库成功")
  }
  else{
  addQuestionBankBatch(selectedQuestionIds.value);
  }
  showQuestionBank.value = false;
  selectedQuestionIds.value = []
  showQuestionBank.value = false
  fetchData()
}




// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  subjectId: null,
  description: '',
  difficulty: 3,
  score: 5,
  isPublic: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入题库名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入题库编码', trigger: 'blur' }],
  subjectId: [{ required: true, message: '请选择所属科目', trigger: 'change' }]
}

// 初始化数据
onMounted(() => {
  fetchData()
  fetchSubjectTree()
})

// 获取科目树
const fetchSubjectTree = async () => {
  try {
    const res = await getSubjectTree();
    subjectOptions.value = res.data
  } catch (error) {
    console.error('获取科目树失败:', error)
  }
}
// 获取表格数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const res = await getQuestionBankPage(params)
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取题库列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.subjectId = null
  handleSearch()
}

// 获取科目名称
const getSubjectName = (id) => {
  const subject = subjectOptions.value.find(item => item.id === id)
  return subject ? subject.name : '未知科目'
}

// 添加题库
const handleAdd = () => {
  dialogTitle.value = '添加题库'
  resetForm()
  dialogVisible.value = true
}

// 编辑题库
const handleEdit = (row) => {
  dialogTitle.value = '编辑题库'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除题库
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该题库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteQuestionBank(id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    subjectId: null,
    description: '',
    difficulty: 3,
    score: 5,
    isPublic: 0,
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (formData.id) {
      await updateQuestionBank(formData)
      ElMessage.success('更新成功')
    } else {
      await addQuestionBank(formData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('操作失败:', error)
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  min-width:100%;
  background: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.operation-panel {
  display: flex;
  width: 100%;

  justify-content: space-between;
  margin-bottom: 20px;
}

.action-buttons {
  margin-left: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
